#include <iostream>
#include <cstring>
#include <unistd.h>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        perror("parameter");
        exit(-1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        perror("connect");
        exit(1);
    }

    while (true)
    {
        std::string cmd_str;
        std::cout << "[client say]# ";
        std::getline(std::cin, cmd_str);
        if (cmd_str.empty())
            continue;

        write(sockfd, cmd_str.c_str(), cmd_str.size());

        char buffer[1024];
        std::string message;
        // while (true)
        // {
        //     ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        //     if (n <= 0)
        //     {
        //         perror("read");
        //         close(sockfd);
        //         exit(1);
        //     }
        //     buffer[n] = 0;
        //     message += buffer;
        //     ssize_t end = message.find("[END]");
        //     if (end != std::string::npos)
        //     {
        //         message.erase(end);
        //         break;
        //     }
        // }
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n <= 0)
        {
            perror("read");
            close(sockfd);
            exit(1);
        }
        buffer[n] = 0;
        message += buffer;
        std::cout << message << std::endl;
    }
    close(sockfd);

    return 0;
}